<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.twoscreen.DeviceConnect"%>
<%@ page import="com.twoscreen.Response"%>
<%@ page import="com.twoscreen.Event"%>
<%@ page import="com.twoscreen.QuestionMulti"%>
<%@ page import="com.twoscreen.TUser"%>
<%@ page import="com.twoscreen.Points"%>
<%@ page import="com.twoscreen.Video"%>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.Text" %>
<%@ page import="java.util.logging.Logger" %>
<%@ page import="java.util.List" %>
<% 
Logger log = Logger.getLogger("com.twoscreen.Points.java");
	//Variables
	String viewerId = null;
	TUser tuser = null;
	String username = null;
	String points = null;
	String correctAnswers = null;
	
	UserService userService = UserServiceFactory.getUserService();
	User user = userService.getCurrentUser();
	String psID = request.getParameter("psID");
	String videoID = request.getParameter("vidId");
	if (videoID != null) {
		correctAnswers = QuestionMulti.getCorrectAnswersByVideoIdJSON(videoID);
	}
	if (user != null) {
		tuser = TUser.getTUser(user); 
		username = tuser.getUserName();
		log.info("username received: " + username);
		points = Points.getPointsTotal(tuser);
		viewerId = tuser.getViewerId();
	}
	Boolean ready = ((user != null) && (psID != null));
	if (ready) {
		//Add the connection
		new DeviceConnect(viewerId, psID);
	}
	String thisURL;
		//If there is a player screen ID append this to the end of the URL that is used for sign in/out
		if (psID != null) {
			thisURL = request.getRequestURL() + "?psID=" + psID;
		} else {
			thisURL = request.getRequestURL().toString();
		}
	String userAgent = request.getHeader("user-agent");
%>
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta http-equiv="cache-control" content="no-store, no-cache, must-revalidate, max-age=1" />
		<meta http-equiv="pragma" content="no-cache" />
		<meta http-equiv="expires" value="1" />
		<title>YouTube Interactive - Interactive Content</title>
		<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> 
		<meta name="apple-mobile-web-app-capable" content="yes" /> <!-- Hides the address bar and bottom navigation on safari when added to home screen -->
		<link rel="shortcut icon" href="/images/favicon.ico" />
		<link rel="apple-touch-startup-image" href="/images/startup.png" /> <!-- Startup image when loading and added to home screen 320x460px -->
		<link rel="apple-touch-icon" href="/images/launch_icon_57.png" />
		<link rel="apple-touch-icon" sizes="72x72" href="/images/launch_icon_72.png" /> 
		<link rel="apple-touch-icon" sizes="114x114" href="/images/launch_icon_114.png" />
		<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
		<link rel="stylesheet" href="/css/app.css" />
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
		<script type="text/javascript" src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
		<script type="text/javascript" src="/js/url-update.js"></script>
		<script type="text/javascript" src='/_ah/channel/jsapi'></script>
		<script type="text/javascript" src="/js/cookie.js"></script>
		<script type="text/javascript" src="/js/interact.js"></script>
		<script type="text/javascript" src="/js/jqBarGraph.1.1.min.js"></script>
		<% if (videoID != null) {  %>
		<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
			{lang: 'en-GB'}
		</script>
		<% } %>
		<script type="text/javascript">
		<% if (ready) {  %>
			var viewer = "<%= viewerId %>";
			var videoID = "<%= videoID %>";
			var pointsObject = <%= QuestionMulti.getPointsJSON(videoID) %>;
		<% } %>
		<% if ( (correctAnswers != null) && !(videoID == null || videoID.equals("null")) ) {  %>
			var ca = <%= correctAnswers %>;
		<% } %>
			if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
				document.title = "Interact";
			}
			function resize() {
				$('.fullWidthRotate').width(function() { return $(window).width(); });
				if (navigator.appName.match(/Explorer/)) {
					document.getElementById("tfl").height = $(window).width()*1.5;
				}
			}
			$(window).resize(function() {
				resize();
			});
			function start() {
				requestToken();
				resize();
			}
		</script>
		<script type="text/javascript"> 
		
		  var _gaq = _gaq || [];
		  _gaq.push(['_setAccount', 'UA-35281811-1']);
		  _gaq.push(['_trackPageview']);
		
		  (function() {
		    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		  })();
		
 		</script>
	</head>
	
<%
	//Logic for displaying page depending if user is logged in and has passed a player screen ID
	if (ready) {
		//The user is authenticated and the player screen is defined = the service is ready
		//Display the content or redirect to the relevant content page
		if ((videoID == null) || (videoID.equals("null"))) {
			//No video ID is passed - Wait for video ID
%>
		<body onload="start();" onunload="">
			<div data-role="page" id="home" data-theme="d">
				<div data-role="header">
					<a href="<%= userService.createLogoutURL(thisURL) %>" data-ajax="false">Log out</a>
					<h1>Two-Screen</h1>
					<a href="#options" data-rel="popup" data-theme="b" class="options">Options</a>
					<div data-role="popup" id="options" data-history="false">
						<ul data-role="listview" data-inset="true" data-theme="b">
							<li data-icon="false">Points <span class="ui-li-count"><%= points %></span></li>
						</ul>
						<div data-role="collapsible" id="username-form" data-theme="b" data-content-theme="c" data-collapsed-icon="arrow-r" data-expanded-icon="arrow-d" style="margin:0;">
							<h2>Edit name</h2>
							<label for="username-input" class="ui-hidden-accessible">Username:</label>
							<input type="text" name="user" id="username-input" value="" placeholder="<%= username %>" data-theme="a" />
							<p id="unError"></p>
							<fieldset id="unSuggestions" data-role="controlgroup">
								<input type="radio" name="radio-choice" id="radio-choice-1" value="choice-1" />
								<label for="radio-choice-1" id="radio-1-label"></label>
								<input type="radio" name="radio-choice" id="radio-choice-2" value="choice-2" />
								<label for="radio-choice-2" id="radio-2-label"></label>
								<input type="radio" name="radio-choice" id="radio-choice-3" value="choice-3" />
								<label for="radio-choice-3" id="radio-3-label"></label>
							</fieldset>
							<button id="username-save" type="submit" data-theme="b" data-icon="check">Save</button>
						</div><!-- /collapsible -->
						<p id="optSuccess"></p>
					</div><!-- /popup -->
				</div>
				<div data-role="content" class="full-screen">
					
<%
	List<Video> videos = Video.getVideoWallData();
	for (Video video : videos) {
		String videoId = video.getKey().getName();
		String imageURL = video.getImageUrlPath();
		String title = video.getVideoTitle();
%>					

					<div class="videoSelection">
						<p><%= title %></p>
						<a href="" onclick="playVideo('<%= videoId %>');"><img src="<%= imageURL %>" alt="img" /></a>
					</div>

<% 
	}
%>


				</div>
			</div>
		</body>

<% 
		} else {
			//Video ID is passed - Load content
%>	
	
		<body onload="requestToken();" onunload="">

<% 
			List<Event> results = Event.getEvents(videoID); //List of content to be displayed for video ID
			if (results.isEmpty()) {
				//No content has been created for this video ID
%>

				<div data-role="page" id="home" data-theme="d">
					<div data-role="header">
						<a href="" data-rel="back" data-icon="arrow-l" data-ajax="false">Videos</a>
						<h1>No content</h1>
						<a href="#options" data-rel="popup" data-theme="b" class="options">Options</a>
						<div data-role="popup" id="options" data-history="false">
							<ul data-role="listview" data-inset="true" style="min-width:250px;" data-theme="b">
								<li data-icon="false">Points <span class="ui-li-count"><%= points %></span></li>
							</ul>
							<div data-role="collapsible" id="username-form" data-theme="b" data-content-theme="c" data-collapsed-icon="arrow-r" data-expanded-icon="arrow-d" style="margin:0;">
								<h2>Edit name</h2>
								<label for="username-input" class="ui-hidden-accessible">Username:</label>
								<input type="text" name="user" id="username-input" value="" placeholder="<%= username %>" data-theme="a" />
								<p id="unError"></p>
								<fieldset id="unSuggestions" data-role="controlgroup">
									<input type="radio" name="radio-choice" id="radio-choice-1" value="choice-1" />
									<label for="radio-choice-1" id="radio-1-label"></label>
									<input type="radio" name="radio-choice" id="radio-choice-2" value="choice-2" />
									<label for="radio-choice-2" id="radio-2-label"></label>
									<input type="radio" name="radio-choice" id="radio-choice-3" value="choice-3" />
									<label for="radio-choice-3" id="radio-3-label"></label>
								</fieldset>
								<button id="username-save" type="submit" data-theme="b" data-icon="check">Save</button>
							</div><!-- /collapsible -->
							<p id="optSuccess"></p>
						</div><!-- /popup -->
					</div><!-- /header -->
					<div data-role="content">
						<div class="center-wrapper">
							<p>The video producer has not created any content for this video.</p>
							<p>Please choose another video from the video wall.</p>
						</div>
					</div><!-- /content -->
				</div>
				
<%
			} else {
				//Loop through the list of content to create the page
				for (Event result : results) {
					String pageId = result.getAction().substring(1);
					String title = result.getTitle();
					Boolean fullScreen = result.getFullScreen();
					Text body = result.getBody();
%>

					<div data-role="page" id="<%= pageId %>" data-theme="d">
						<div data-role="header">
							<a href="" data-rel="back" data-icon="arrow-l" data-ajax="false">Videos</a>
							<h1><%= title %></h1>
							<a href="" onclick="playStop();" data-theme="b">Play/Stop</a>
						</div><!-- /header -->
						<div data-role="content" <%if (fullScreen) {%>class="full-screen"<%}%>>
							<%= body.getValue() %>
						</div><!-- /content -->
					</div>

<%
				}
				List<QuestionMulti> multiChoiceQuestions = QuestionMulti.getByVideoId(videoID);
				if (!multiChoiceQuestions.isEmpty()) {
					for (QuestionMulti mQuestion : multiChoiceQuestions) {
						long qid = mQuestion.getKey().getId();
%>

					<div data-role="page" id="respTo<%= qid %>" class="responses" data-theme="d">
						<div data-role="header">
							<a href="" data-rel="back" data-icon="arrow-l" data-ajax="false">Videos</a>
							<h1>Responses</h1>
							<a href="" onclick="playStop();" data-theme="b">Play/Stop</a>
						</div><!-- /header -->
						<div data-role="content" class="full-screen">
							<p id="responseFeedback-<%= qid %>">We didn't receive a response from you, here is what others thought (correct answer in green):</p>
							<div class="center-wrapper">
								<div class="results" id="results-q<%= qid %>"></div>
							</div>
							<script type="text/javascript">
								tableData = new Array(<%= Response.getRepliesJQBar(qid) %>);
								$('#results-q<%= qid %>').jqBarGraph({ data: tableData, width: 300 });
								//http://workshop.rs/jqbargraph/ 
							</script>
						</div><!-- /content -->
					</div>

<%
					}
				}
			}
		}
%>			
		
		
<%
	} else if ((user != null) && (psID == null)) {
		//The user is authenticated and no Player Screen is defined
		//Ask the user to enter the screen ID or to scan from their QR code scanner
%>
		<body onload="iniOptionsMenu();" onunload="">
			<div data-role="page" id="home" data-theme="d">
				<div data-role="header">
					<a href="<%= userService.createLogoutURL(thisURL) %>" data-ajax="false">Log out</a>
					<h1>Two-Screen</h1>
					<a href="#options" data-rel="popup" data-theme="b" class="options">Options</a>
					<div data-role="popup" id="options" data-history="false">
						<ul data-role="listview" data-inset="true" style="min-width:250px;" data-theme="b">
							<li data-icon="false">Points <span class="ui-li-count"><%= points %></span></li>
						</ul>
						<div data-role="collapsible" id="username-form" data-theme="b" data-content-theme="c" data-collapsed-icon="arrow-r" data-expanded-icon="arrow-d" style="margin:0;">
							<h2>Edit name</h2>
							<label for="username-input" class="ui-hidden-accessible">Username:</label>
							<input type="text" name="user" id="username-input" value="" placeholder="<%= username %>" data-theme="a" />
							<p id="unError"></p>
							<fieldset id="unSuggestions" data-role="controlgroup">
								<input type="radio" name="radio-choice" id="radio-choice-1" value="choice-1" />
								<label for="radio-choice-1" id="radio-1-label"></label>
								<input type="radio" name="radio-choice" id="radio-choice-2" value="choice-2" />
								<label for="radio-choice-2" id="radio-2-label"></label>
								<input type="radio" name="radio-choice" id="radio-choice-3" value="choice-3" />
								<label for="radio-choice-3" id="radio-3-label"></label>
							</fieldset>
							<button id="username-save" type="submit" data-theme="b" data-icon="check">Save</button>
						</div><!-- /collapsible -->
						<p id="optSuccess"></p>
					</div><!-- /popup -->
				</div><!-- /header -->
				<div data-role="content">
					<p><%= user.getNickname() %>, you are one step away from the best in
						interactive content from your favourite YouTube videos!
					</p>
					<p>We just need to know the screen ID you are watching:</p>
					<form action="index.jsp" data-ajax="false">
						<input type="text" name="psID" />
						<input type="submit" value="Interact!" />
					</form>
				</div><!-- /content -->
			</div>
		</body>
<%
	} else if ((user == null) && (psID != null)) {
		//The user is not authenticated and a Player Screen is passed
		
		//The user could have reached this page by signing out - destroy the token cookies
		Cookie removeChtoken = new Cookie("chtoken", null);
		removeChtoken.setMaxAge(0);
		removeChtoken.setPath("/");
		response.addCookie(removeChtoken);
		
		//Ask the user to sign up or sign in - show benefits
		//Redirect to here where option 2 should be chosen
%>
		<body onunload="">
			<div data-role="page" id="home" data-theme="d">
				<div data-role="header">
					<a href="<%= userService.createLoginURL(thisURL) %>" data-ajax="false">Log in</a>
					<h1>Two-Screen</h1>
				</div><!-- /header -->
				<div data-role="content">       
					<p>Once you are signed in we can send you on your way to the glorious interactive content!</p>
					<h3><a href="<%= userService.createLoginURL(thisURL) %>" data-ajax="false">Why not sign in now with your Google account to get started?</a></h3>
				</div><!-- /content -->
			</div>
		</body>
<%
	} else {
		//The user is not set and the player screen is not set
		
		//The user could have reached this page by signing out - destroy the token cookies
		Cookie removeChtoken = new Cookie("chtoken", null);
		removeChtoken.setMaxAge(0);
		removeChtoken.setPath("/");
		response.addCookie(removeChtoken);
		
		//The user has possibly arrived from google - explain benefits to service and offer sign up/in
		//Redirect here where option 2 should be selected
%>
		<body onunload="">
			<div data-role="page" id="home" data-theme="d">
				<div data-role="header">
					<a href="<%= userService.createLoginURL(thisURL) %>" data-ajax="false">Log in</a>
					<h1>Two-Screen</h1>
				</div><!-- /header -->
				<div data-role="content">       
					<p>Hello! this page is for generating interactive content for YouTube videos.</p>
					<p>Did you know there are loads of YouTube videos that are currently interactive?</p>
					<p>All you need is to get the internet hooked up to your TV or other big screen, navigate to two-screen.appspot.com,
						scan the QR code with this device, and that will take you to a special page set up to let
						you communicate with your friends and everyone else watching that video, as well as many other cool
						things listed below!</p>
					<ul>
						<li>Take part in TV quizzes to win badges and play against your friends</li>
						<li>Get extra information about what you are watching</li>
						<li>Chat with friends online about the show</li>
						<li>See exclusive behind the scenes videos and pictures</li>
					</ul>
					<h3><a href="<%= userService.createLoginURL(thisURL) %>" data-ajax="false">Why not sign in now with your Google account to get started?</a></h3>
				</div><!-- /content -->
			</div>
		</body>
<%
	}
%>

</html>